package com.ah.suams.filter;

import com.ah.suams.dto.LoginToken;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class AutoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;

        Map<String, LoginToken> loginTokenMap = (HashMap)httpServletRequest.getServletContext().getAttribute("loginTokenMap");
        Cookie[] cookies = httpServletRequest.getCookies();

        String autoLoginToken = null;
        for(Cookie cookie : cookies){
            if("autoLoginCookie".equals(cookie.getName())){
                autoLoginToken = cookie.getValue();
            }
        }

        if(loginTokenMap != null && autoLoginToken != null){
            //获取用户
            //存入session
            LoginToken loginToken = loginTokenMap.get(autoLoginToken);
            httpServletRequest.getSession().setAttribute("admin",loginToken.getAdmin());

            filterChain.doFilter(request,response);
        }else{
            //没有自动登录
            httpServletResponse.sendRedirect("/toLogin");
        }
    }

    @Override
    public void destroy() {

    }
}
